import { FarrisDesignBaseComponent } from '@farris/designer-element';
import { ListFilterSchema } from '../schema/schema';
import { ElementPropertyConfig } from '@farris/ide-property-panel';
import { ListFilterProp } from '../property/property-config';
import { ListFilterItemComponent } from './filter-item/component/fd-filter-item';
import { FormPropertyChangeObject } from '../../../../entity/property-change-entity';
import { RowNode } from '@farris/ui-treetable';
import { ListFilterContextMenuManager } from '../context-menu/context-menu.manager';
import { ControlCssLoaderUtils } from '../../../../utils/control-css-loader';
import { DomService, DesignerEnvType, FormBasicService, WebCmdService, SchemaService, FormSchemaEntityField$Type } from '@farris/designer-services';
import { NoCodeListFilterProp } from '../property/nocode-property-config';
import { ListFilterFieldTypeEnums } from '../property/editor/list-filter-fields-editor/query-data/field-control-types';
import { ListFilterFieldCreator } from '../property/editor/list-filter-fields-editor/query-data/field-control-data';

export default class FdListFilterComponent extends FarrisDesignBaseComponent {

    // 展示在界面上的控件模板字符串
    filterControlTpls = '';

    // 默认收起到右侧的字段，不展示在页面上
    extendFilterList = [];

    // 展示在界面上的字段
    showInPageFilterList = [];

    constructor(component: any, options: any) {
        super(component, options);

        // 加载css相关文件
        ControlCssLoaderUtils.loadCss('list-filter.css');
    }

    getDefaultSchema(): any {
        return ListFilterSchema;
    }


    getStyles(): string {
        let style = 'display:block;';
        if (this.component.controlSource === 'light') {
            style += 'flex-grow: 1;flex-shrink: 1;flex-basis: 0;max-width: 100%;';
        }
        return style;
    }

    init(): void {
        this.checkFieldSchemaAndControl();
    }

    render(): any {
        this.assembleFilterControls();

        return super.render(this.renderTemplate('ListFilter', {
            component: this.component,
            filterControlTpls: this.filterControlTpls,
            // 展示在界面上的控件
            showInPageFilterList: this.showInPageFilterList,
            // 收起的控件
            extendFilterList: this.extendFilterList,
            // 是否展示收起图标
            showMoreIcon: this.extendFilterList.length > 0,
            // 展示在外部的控件个数
            showFilterListLength: this.component.filterList ? this.component.filterList.length - this.extendFilterList.length : 0
        }));
    }

    /**
     * 构造筛选项
     */
    private assembleFilterControls(): void {
        const filterList = this.component.filterList || [];

        this.extendFilterList = [];
        this.showInPageFilterList = [];
        this.filterControlTpls = '';

        filterList.forEach(filterConfig => {
            if (!filterConfig.control || !filterConfig.control.controltype) {
                return;
            }
            if (filterConfig.control.isExtend) {
                this.extendFilterList.push(filterConfig);
            } else {
                this.showInPageFilterList.push(filterConfig);

                // 常规筛选需要渲染出独立的筛选项
                if (this.component.controlSource === 'normal') {
                    const itemTemplate = this.renderNormalItem(filterConfig);
                    this.filterControlTpls += ' ' + itemTemplate;
                }

            }

        });
    }

    /**
     * 常规筛选：渲染单个输入框
     * @param filterConfig 配置数据
     */
    private renderNormalItem(filterConfig: any): any {
        const inputProp = Object.assign({}, {
            controltype: filterConfig.control.controltype,
            require: filterConfig.control.required,
            enumData: filterConfig.control.enumValues,
            items: filterConfig.control.enumValues,
            placeHolder: filterConfig.placeHolder || '',
            beginPlaceHolder: filterConfig.beginPlaceHolder || '',
            endPlaceHolder: filterConfig.endPlaceHolder || '',
            isHorizontal: true,
            groupText: filterConfig.control.groupText
        });
        const itemComponent = new ListFilterItemComponent(inputProp, this.options, this);

        return itemComponent.renderItem(filterConfig);
    }

    attach(element: any): any {
        const superAttach: any = super.attach(element);

        const domService = this.options.designerHost.getService('DomService') as DomService;

        // 将各筛选项追加到domservice的map中，目的是为了在交互面板【已绑定命令】中展示路径信息
        const filterList = this.component.filterList || [];
        filterList.forEach(filterConfig => {
            if (!filterConfig.control || !filterConfig.control.controltype) {
                return;
            }
            domService.controlBasicInfoMap.set(filterConfig.control.id, {
                showName: filterConfig.name,
                parentPathName: `筛选条 > ${filterConfig.name}`
            });
        });
        return superAttach;
    }

    /**
     * 属性面板构造数据
     */
    getPropertyConfig(): ElementPropertyConfig[] {
        const serviceHost = this.options.designerHost;
        const formBasicService = serviceHost.getService('FormBasicService') as FormBasicService;
        if (formBasicService.envType === DesignerEnvType.noCode) {
            const prop: NoCodeListFilterProp = new NoCodeListFilterProp(serviceHost, this.viewModelId, this.componentId);
            const propertyConfig: ElementPropertyConfig[] = prop.getPropConfig(this.component);
            return propertyConfig;
        } else {
            const prop: ListFilterProp = new ListFilterProp(serviceHost, this.viewModelId, this.componentId);
            const propertyConfig: ElementPropertyConfig[] = prop.getPropConfig(this.component);
            return propertyConfig;
        }


    }


    /**
     * 属性变更后事件
     * @param changeObject 变更集
     */
    onPropertyChanged(changeObject: FormPropertyChangeObject): void {
        const unMappingPropIds = ['visible', 'disable', 'binding', 'showReminder'];

        if (!unMappingPropIds.includes(changeObject.propertyID)) {
            this.triggerRedraw();
        }


        // 涉及到字段绑定事件的变更，故触发同步actions操作
        if (changeObject.propertyID === 'filterList') {
            const webCmdService = this.options.designerHost.getService('WebCmdService') as WebCmdService;
            webCmdService.syncActions();
        }
    }


    /**
     * 组装右键菜单
     * @param rowNode 组件在控件树上对应的行数据
     */
    resolveContextMenuConfig(rowNode: RowNode) {
        const menuManager = new ListFilterContextMenuManager(this, rowNode);
        return menuManager.setContextMenuConfig();
    }
    /**
     * 禁止移动
     */
    checkCanMoveComponent(): boolean {
        return false;
    }

    /**
     * 删除筛选条时连带删除上层容器
     */
    onRemoveComponent() {
        const parentSchema = this.parent && this.parent.component;
        if (!parentSchema) {
            return;
        }
        const parentClass = parentSchema.appearance ? parentSchema.appearance.class : '';
        const parentClassList = parentClass ? parentClass.split(' ') : [];

        const grandParent = this.parent.parent;
        const grandParentSchema = grandParent && grandParent.component;

        // 上层为筛选条容器，则需要将容器一同移除
        if (grandParentSchema && parentClassList.includes('f-filter-container')) {
            const filterContainerIndex = grandParentSchema.contents.findIndex(c => c.id === parentSchema.id);
            if (filterContainerIndex > -1) {
                grandParentSchema.contents.splice(filterContainerIndex, 1);
                // 为了后续触发重绘的父级组件，返回筛选条容器的父级容器
                return { parentComponentInstance: grandParent };
            }

        }

    }
    /**
     * 检查字段类型与控件类型的适配度
     */
    private checkFieldSchemaAndControl() {
        const schemService = this.options.designerHost.getService('SchemaService') as SchemaService;
        this.component.filterList.forEach(fieldConfig => {
            if (!fieldConfig.id || !fieldConfig.control || !fieldConfig.labelCode) {
                return;
            }
            const schemaField = schemService.getSchemaField('path', fieldConfig.labelCode);
            // 1、字段不存在：自动删除
            if (!schemaField) {
                fieldConfig.isInValid = true;
                return;
            }
            // 2、字段由简单字段变更为复杂字段：自动删除
            if (schemaField.$type === FormSchemaEntityField$Type.ComplexField) {
                fieldConfig.isInValid = true;
                return;
            }
            const schemaFieldType = schemaField.type.name;
            const allowedQueryControlTypes = ListFilterFieldTypeEnums.getControlTypeEnum(schemaFieldType, this.component.controlSource);
            if (!allowedQueryControlTypes.find(type => type.key === fieldConfig.control.controltype)) {
                // 3、字段类型与控件类型不匹配：自动替换控件
                const newControl = ListFilterFieldCreator.getFilterField(schemaField);
                Object.assign(fieldConfig, newControl);
            }

        });
        this.component.filterList = this.component.filterList.filter(config => !config.isInValid);
    }
}
